package com.kintreda.ieco_server.util.file;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class FileUpload {


    /**
     * @param file //文件对象
     * @param filePath //上传路径
     * @param fileName //文件名
     * @return 文件名
     */
    public static String fileUp(MultipartFile file, String filePath, String fileName) {
        String extName = ""; // 扩展名格式：
        try {
            if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
                extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            }
            copyFile(file.getInputStream(), filePath, fileName + extName).replaceAll("-", "");
        } catch (IOException e) {
            System.out.println(e);
        }
        return fileName + extName;
    }

    /**
     * 写文件到当前目录的upload目录中
     * @param in
     * @param dir
     * @param realName
     * @return
     * @throws IOException
     */
    private static String copyFile(InputStream in, String dir, String realName) throws IOException {
        File file = new File(dir, realName);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        FileUtils.copyInputStreamToFile(in, file);
        return realName;
    }


    /**
     * uploadify图片上传 返回图片名称集合
     * @param request
     * @throws IOException
     */
    @SuppressWarnings("unused")
    public static Map<String, Object> uploadByUploadifyMap(HttpServletRequest request) throws IOException {//,String filePath
        Map<String, Object> map = new HashMap<String, Object>();
        //String filePath = request.getSession().getServletContext().getRealPath("/")+ UPLOADPRODIR +"/"+fileFloder();;
        String filePath = "d:/upload/test/";
        //System.out.println(filePath);
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)request;

        Map<String, MultipartFile> fileMap = mRequest.getFileMap();
        File f = new File(filePath);
        if(!f.exists()){
            f.mkdirs();
        }
        int i = 0;
        String fileName = null;
        for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext(); i++) {
            Map.Entry<String, MultipartFile> entry = it.next();
            MultipartFile mfile = entry.getValue();
            fileName = mfile.getOriginalFilename();
            String storeName = rename(fileName);
            map.put(entry.getKey(),storeName);
            //fileNames.add(fileFloder()+storeName);
            File destFile = new File(filePath,storeName);
            InputStream in = mfile.getInputStream();
            OutputStream out = new FileOutputStream(destFile);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = in.read(buf))!=-1) {
                out.write(buf,0,len);
            }
            out.flush();
            out.close();
        }
        return map;
    }

    private static String rename(String name) {
        Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        Long random = (long)(Math.random()*now);
        String fileName = now +""+random;
        if(name.indexOf(".")!=-1){
            fileName += name.substring(name.lastIndexOf("."));
        }
        return fileName;
    }

}
